currentInput = null
searchContent = null//在此界面点击溯源时input中的内容
var maxLetterLength = 0//需要显示的节点text的最大长度
var singleLineLetters = 5//事件树节点每行显示的text的长度
var root = {
}//事件树数据
var currentOperationNode = root
//获得传过来的login与在数据库中对应的表单
var paras = location.search;            //search获得地址中的参数，内容为'?itemId=12'
var result = paras.match(/[^\?&]*=[^&]*/g);     //match是字符串中符合的字段一个一个取出来，result中的值为['login=xx','table=admin']
paras = {};                    //让paras变成没有内容的json对象
for(i in result){
    var temp = result[i].split('=');    //split()将一个字符串分解成一个数组,两次遍历result中的值分别为['itemId','xx']
    paras[temp[0]] = temp[1];
}
var content = decodeURI(paras.content); //根据参数名"itemId"，获取参数值

var questions = JSON.parse(content)
console.log(questions)

var localResult//保存列表数据
var loacalDetail//保存当前显示的详情数据
var historyDecompose = []

initLayout()
renderTree()

function initLayout() {
    $('#search-input').val(questions.origin_question)
    hideDecompose()

    showLoading()
    http_tls()
    // mask_http_tls()
}

function getJsonData() {
    var json = {
        "QuestionList":questions.questions
    }
    return JSON.stringify(json)
}

function clickResultItem(i, j) {
	hideListAndShowDetail()
	renderDetail(i, j)
}

function hideListAndShowDetail() {
	$(".result_list").css('display', "none")
	$(".detail").css('display', "flex")
}

function hideDetailAndShowList() {
    $(".result_list").css('display', "flex")
    $(".detail").css('display', "none")
}

//i指点击的第i个问题的文档列表，j指点击的文档在文档列表中的位置
function renderDetail(i, j) {
	renderLeftList(i, j)
	renderRightContent(i, j)
}

function renderLeftList(i, j) {
    if (currentOperationNode['children'] && currentOperationNode['children'].length !== 0) {
        currentOperationNode.children[i]['children'] = []
        var newChild = {
            'name': localResult.timelines[i][j].time,
            'children': []
        }
        currentOperationNode.children[i]['children'].push(newChild)
        currentOperationNode = newChild
        refreshTree()
    } else {
        treeAppendItem(localResult.timelines[i][j].time)
    }

    var detailList = ""
    detailList += `
    <div class="result_item_title"><span class="item_name">"${questions.questions[i]}"</span>检索结果</div>
    <div class="questions list-group pre-scrollable">
    `
    itemCount = localResult.timelines[i].length
    for (index = 0; index < itemCount; index++) {
        //参数中有j，为避免冲突，循环变量改为index
        detailList += `
        <button onclick="clickResultItem(${i}, ${index})" type="button" class="list-group-item item">${index + 1}.${localResult.timelines[i][index].time}
            <div class="item_content">${localResult.timelines[i][index].text}</div>
        </button>
        `
    }
    detailList += `</div>`
    $('.detail_list').html(detailList)
}

function renderRightContent(i, j) {
    http_sim_doc(i, j)
}

function http_sim_doc(i, j) {
    var jsonStr = get_sim_doc_params(i, j)
    http_sim_doc_with_param_str(jsonStr)
}

function http_sim_doc_with_param_str(paramStr) {
    showLoading()
    console.log(`请求json${paramStr}`)
    $.ajax({
         type: "POST",
         url: "http://172.18.31.218:20001/api/v1/get_detail",
         contentType: "application/json; charset=utf-8",
         data: paramStr,
         dataType: "json",
         success: function (ret) {
            hideLoading()
            console.log("返回结果 : " + JSON.stringify(ret))
            if (ret.length == 0) {
                alert('get_detail返回为空')
                return
            }
            loacalDetail = ret
            $('.content .title').html(ret.title)
            $('.content .source').html(`来源：${formatSource(ret.source)}，时间：${ret.time.substring(0, 10)}`)
            $('.content .desc').html(ret.content)
            renderSimilar(ret)
            renderSameSource(ret)
            renderVideo(ret)
            
         },
         error: function (err) {
            hideLoading()
             alert('网络请求失败')
         }
     });
}

function renderVideo(ret) {
    var videoList = ""
    videoList += `
    <div class="similiar_title">相似的视频</div>
    <div class="similiars list-group pre-scrollable">
    `
    itemCount = ret.relate_source.length
    for (index = 0; index < itemCount; index++) {
        //参数中有j，为避免冲突，循环变量改为index
        videoList += 
        `
        <button onclick="clickVideoItem(${index})" type="button" class="list-group-item item"><span class='item_content'>${index + 1}.${ret.relate_source[index][1]}</span></button>
        `
    }
    videoList += `</div>`
    $('.video_item').html(videoList)
}

function renderSameSource(ret) {
    var sameSourceList = ""
    sameSourceList += `
    <div class="similiar_title">相同来源的文档</div>
    <div class="similiars list-group pre-scrollable">
    `
    itemCount = ret.relate_source.length
    for (index = 0; index < itemCount; index++) {
        //参数中有j，为避免冲突，循环变量改为index
        sameSourceList += 
        `
        <button onclick="clickSameSourceItem(${index})" type="button" class="list-group-item item"><span class='item_content'>${index + 1}.${ret.relate_source[index][1]}</span></button>
        `
    }
    sameSourceList += `</div>`
    $('.source_item').html(sameSourceList)
}

function renderSimilar(ret) {
    var similiarList = ""
    similiarList += `
    <div class="similiar_title">相似的文档</div>
    <div class="similiars list-group pre-scrollable">
    `
    itemCount = ret.relate.length
    for (index = 0; index < itemCount; index++) {
        //参数中有j，为避免冲突，循环变量改为index
        similiarList += 
        `
        <button onclick="clickSimiliarItem(${index})" type="button" class="list-group-item item"><span class='item_content'>${index + 1}.${ret.relate[index][0]}</span></button>
        `
    }
    similiarList += `</div>`
    $('.similar_item').html(similiarList)
}

function treeAppendItem(displayWords) {
    currentOperationNode['children'] = []
    var newChild = {
        'name': displayWords,
        'children': []
    }
    currentOperationNode['children'].push(newChild)
    currentOperationNode = newChild
    refreshTree()
}

function clickSimiliarItem(index) {
    if (loacalDetail != null) {
        treeAppendItem('相似文档')
        id = loacalDetail.relate[index][2]
        jsonStr = getJsonfromId(id)
        http_sim_doc_with_param_str(jsonStr)
    }
}

function clickSameSourceItem(index) {
    if (loacalDetail != null) {
        treeAppendItem('同来源文档')
        id = loacalDetail.relate_source[index][0]
        jsonStr = getJsonfromId(id)
        http_sim_doc_with_param_str(jsonStr)
    }
}

function showLoading() {
    $('.loading').show()
}

function hideLoading() {
    $('.loading').hide()
}

function showDecompose() {
    $('.mydecompose').show()
}

function hideDecompose() {
    $('.mydecompose').hide()
}

function clickVideoItem(index) {
    if (loacalDetail != null) {
        treeAppendItem('相似视频')
        id = loacalDetail.relate_source[index][0]
        jsonStr = getJsonfromId(id)
        http_sim_doc_with_param_str(jsonStr)
    }
}

function getJsonfromId(id) {
    var json = {
        "id":id
    }
    return JSON.stringify(json)
}

function formatSource(source) {
    if (source.length >= 10) {
        return source.substring(0, 10) + "..."
    }
    return source
}

function get_sim_doc_params(i, j) {
    // console.log(localResult.timelines[i][j])
    var json = {
        "id":localResult.timelines[i][j].docId
    }
    return JSON.stringify(json)
}

function http_question_extend(jsonStr) {
    console.log(jsonStr)
    $.ajax({
         type: "POST",
         url: "http://172.18.31.218:9991/questionExtend",
         contentType: "application/json; charset=utf-8",
         data: jsonStr,
         dataType: "json",
         success: function (ret) {
            hideLoading()
            console.log("问题分解结果 : " + JSON.stringify(ret))
            if(ret.code == 200) {
                var questionList = ret.data.extendItemList

                questionList.sort(function(a, b){
                    if (a.score >= b.score) {
                        return -1
                    } else {
                        return 1
                    }
                })
                // console.log(questionList.length)
                $('#questions').empty()
                for (i = 0; i < questionList.length; i++) {
                    $('#questions').append(`<button onclick="clickQuestion(this)" type="button" class="list-group-item item"><span>${i + 1}</span>.<span>${questionList[i].topic}</span></button>`)
                }
            } else {
                alert(ret.message)
            }
             
         },
         error: function (err) {
            hideLoading()
             alert('网络请求失败')
         }
    })
}

function mask_http_tls() {
    hideLoading()
    retStr = 
    `
    {"timelines":[[{"docId":"611dfd57decabc5de05335fc","text":"对于中日双边服务贸易而言，一方面，日本传统服务业竞争力较强，旅游、交通等传统服务贸易对华出口量持续增长；另一方面，虽然我国知识密集型服务国际竞争力有所增强，但日本知识密集型服务竞争力一直较为稳定，对我国的知识密集型服务进口需求不如我国对日传统服务贸易进口需求，使得双方服务贸易互补性不高，也拉大了我国对日服务贸易逆差","time":"2021-09-06"},{"docId":"5ff42ba3fbf492756aeb019f","text":"随着新西兰总理阿德恩决定退出近期中澳的争端,新西兰新任外交大臣纳纳亚·马哈塔(Nanaia Mahuta)却强调将重新介入中澳关系,愿意帮助邻国澳大利亚推动停战谈判,表示在今年新西兰主办的APEC峰会上会提供使双方共同参加会议的机会,而新西兰愿意创造不同的环境并帮助两国重新展开经济与贸易对话","time":"2021-01-05"},{"docId":"5f505f067c516787306e5327","text":"2019年11月,德国防长卡伦鲍尔(Annegret Kramp-Karrenbauer)曾宣称,澳大利亚、日本、韩国、印度等德国在印太地区的伙伴,正感受到“中国对权力的主张愈发侵犯他们的利益”,“是时候让德国发出信号,与我们的盟友一同出现在该地区了","time":"2020-09-03"},{"docId":"611330e2d08992235b4e705e","text":"(四)美国政局变化为其加强介入台湾问题提供了内部动力特朗普作为共和党候选人当选美国总统,其外交政策不可避免地受到所属党派的影响.共和党一直持保守和对华强硬立场,大选期间,共和党在提名大会推出的体现该党主流观点的竞选纲领中,即严厉指责中国的货币政策、知识产权保护和在南海的行为,并对中美关系改善持消极态度②.关于台湾问题,共和党认为美台关系建立在?与台湾关系法?之上,坚持美国应支持保障台湾安全.在２０１６年７月全国代表大会上,共和党更是首次将美国对台所谓“六项保证”纳入党纲,并支持对台出售“防御性”武器,包括建造常规柴电潜艇的技术③.鉴于共和党还同时掌握参众两院,因而将在很大程度上影响特朗普的对台政策.另一方面,特朗普个人和团队政治理念的影响也不容忽视,其本人对华态度远谈不上友好,多次在汇率问题、关税问题、南海问题上指责中国,宣称“中国对自己的货币贬值,对我们的产品征收重税,或者在南海中部修建大规模军事设施———如果问我们这样到底可不可以?我认为不可以.”①在台湾问题上,特朗普团队部分人员对华也具有明显的敌意,其亚太政策顾问纳瓦罗大选前在?国家利益?杂志上发文,即对中国在亚太日益增长的影响提出警告,认为大陆与台湾军事实力差距悬殊,奥巴马政府涉台政策置台湾安全于不顾,应增加对台军售以平衡两岸军力对比②.目前,虽然特朗普在“一个中国”政策上态度缓和,但由于其任用的政府高层多为对华强硬派和亲台派,故而在台湾问题上不能对其期望过高","time":"2020-06-10"}]]}
    `
    console.log(retStr)
    ret = JSON.parse(retStr)
    console.log("返回结果 : " + JSON.stringify(ret))
    if (ret.length == 0) {
        alert('tls返回为空')
        return
    }
    localResult = ret
    count = ret.timelines.length
    var resultItemList = ''
    for (i = 0; i < count; i++) {
        var resultItem = 
        `
        <div class="result_item">
        <div class="result_item_title"><span class="item_name">"${questions.questions[i]}"</span>检索结果</div>
        <div class="questions list-group pre-scrollable">
        `
        itemCount = ret.timelines[i].length
        for (j = 0; j < itemCount; j++) {
            resultItem += `<button onclick="clickResultItem(${i}, ${j})" type="button" class="list-group-item item">${j + 1}.${ret.timelines[i][j].time}<div class="item_content">${ret.timelines[i][j].text}</div></button>`
        }
        resultItem += `</div></div>`
        resultItemList += resultItem
    }
    $('.result_list').html(resultItemList)
}

function http_tls() {
    showLoading
    var jsonStr = getJsonData()
    console.log(`请求json${jsonStr}`)
    $.ajax({
         type: "POST",
         url: "http://172.18.31.218:20001/api/v1/tls",
         contentType: "application/json; charset=utf-8",
         data: jsonStr,
         dataType: "json",
         success: function (ret) {
            hideLoading()
            console.log("返回结果 : " + JSON.stringify(ret))
            if (ret.length == 0) {
                alert('tls返回为空')
                return
            }
            localResult = ret
            count = ret.timelines.length
            var resultItemList = ''
            for (i = 0; i < count; i++) {
                var resultItem = 
                `
                <div class="result_item">
                <div class="result_item_title">"<span class="item_name">${questions.questions[i]}</span>"检索结果</div>
                <div class="questions list-group pre-scrollable">
                `
                itemCount = ret.timelines[i].length
                for (j = 0; j < itemCount; j++) {
                    resultItem += `<button onclick="clickResultItem(${i}, ${j})" type="button" class="list-group-item item">${j + 1}.${ret.timelines[i][j].time}<div class="item_content">${ret.timelines[i][j].text}</div></button>`
                }
                resultItem += `</div></div>`
                resultItemList += resultItem
            }
            $('.result_list').html(resultItemList)
         },
         error: function (err) {
            hideLoading()
             alert('网络请求失败')
         }
     });
}

function toDecompose() {
    clearOldQuestions()
    showDecompose()
    searchContent = $("#search-input").val()
    if (searchContent.length == 0) {
        alert("请输入搜索信息")
        return
    }
    $("#origin_question").html(searchContent)
    historyDecompose.push(searchContent)
    treeAppendItem(searchContent)
    var jsonStr = getDecomposeStr(searchContent)
    http_question_extend(jsonStr)
}

function clearOldQuestions() {
    $("#input_questions").empty()
    // count = $("#input_questions").children().length;
    // console.log(count)
    $("#input_questions").append(`<div class="sub_question"><span class="decompose_title">子问题${1}：</span><input onclick="clickInput(this)"><div onclick="deleteSubQuestion(this)" class="delete"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span><span class="end">删除</span></div></div>`)
}

function getDecomposeStr(searchContent) {
    var json = {
        "extendText": searchContent
    }
    return JSON.stringify(json)
}

function clickInput(event) {
    currentInput = event
}

function clickQuestion(event) {
    if (currentInput != null) {
        myContent = $($(event).children()[1]).html()
        $(currentInput).val(myContent)
    }
}

function deleteSubQuestion(obj) {
    $(obj).parent().remove()
    refreshIndex()
}
function refreshIndex() {
    size = $("#input_questions").children().length
    for (i = 0; i < size; i++) {
        currentQuestion = $("#input_questions").children()[i]
        currentSpan = $(currentQuestion).children()[0]
        $(currentSpan).html(`子问题${i + 1}：`)
    }
}

function renderTree() {
    root['name'] = questions.origin_question
    if (maxLetterLength < questions.origin_question.length) {
        maxLetterLength = questions.origin_question.length
    }
    root['children'] = []
    for (i = 0; i < questions.questions.length; i++) {
        root['children'].push({'name': questions.questions[i]})
        if (maxLetterLength < questions.questions[i].length) {
            maxLetterLength = questions.questions[i].length
        }
    }
    refreshTree()
}

function refreshTree() {
    $('.tree').empty()
    var width = 500,
        height = 500;
    var tree = d3.layout.tree()
        .size([360, 320])
        .separation(function (a, b) {
            return (a.parent == b.parent ? 1 : 2)
        });

    var diagonal = d3.svg.diagonal()
        .projection(function (d) {
            return [d.x, d.y]
        });

    var svg = d3.select("div.tree").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(40,40)");

    var nodes = tree.nodes(root);
    var links = tree.links(nodes);

    // console.log(nodes);
    // console.log(links);

    var link = svg.selectAll(".link")
        .data(links)
        .enter()
        .append("path")
        .attr("class", "link")
        .attr("d", diagonal);

    var node = svg.selectAll(".node")
        .data(nodes)
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function (d) {
            return "translate(" + d.x + "," + d.y + ")";
        })

    node.append("circle")
        .attr("r", 4.5);

    mText = node.append("text")

    console.log(`maxLetterLength ${maxLetterLength}`)
    var lineCount = parseInt((maxLetterLength + singleLineLetters - 1) / 5)
    console.log(`lineCount ${lineCount}`)

    for (index = 0; index < lineCount; index++) {
        if (index == 0) {
            mText.append("tspan")
                .attr("x", function (d) {
                    return 10;
                })
                .text(function (d) {
                    return handleText(d, index)
                })
        } else {
            mText.append("tspan")
                .attr("x", function (d) {
                    return 10;
                })
                .attr("dy", '15px')
                .text(function (d) {
                    return handleText(d, index)
                })
        }

    }
}

function handleText(d, i) {
    if (d.name.length > i * singleLineLetters && d.name.length < (i + 1) * singleLineLetters) {
        // console.log(`111   ${i*5} ${d.name.length}`)
        // console.log(d.name.substring(i * singleLineLetters, d.name.length))
        return d.name.substring(i * singleLineLetters, d.name.length)
    } else if (d.name.length > i * singleLineLetters) {
        // console.log(`222   ${i*5} ${i*5 + 5}`)
        // console.log(d.name.substring(i * 5, i * 5 + 5))
        return d.name.substring(i * singleLineLetters, i * singleLineLetters + 5)
    }
    return ""
}

$(document).ready(function(){
    $("#decompose").click(function(){
        var json = {}
        var quesArray = []
        count = $("#input_questions").children().length
        for (i = 0; i < count; i++) {
            question = $($($("#input_questions").children()[i]).children('input')[0]).val()
            quesArray.push(question)
        }
        json['questions'] = quesArray
        // console.log(content)
        json['origin_question'] = searchContent
        if (quesArray.length <= 0) {
            alert('请在分解问题列表中选择若干问题')
            return
        }

        //绘制事件树但不改变currentOperationNode
        currentOperationNode['children'] = []
        for (i = 0; i < count; i++) {
            question = $($($("#input_questions").children()[i]).children('input')[0]).val()
            var newChild = {
                'name': question,
                'children': []
            }
            currentOperationNode['children'].push(newChild)
        }
        refreshTree()

        questions = json
        initLayout()
        hideDetailAndShowList()
        // window.location.href="SearchResult.html?" + "content=" + encodeURI(JSON.stringify(json))
    });
});
$(document).ready(function(){
    $("#direct").click(function(){
        if (searchContent == null || searchContent.length <= 0) {
            alert('当前没有问题')
            return
        }
        var json = {}
        var quesArray = [searchContent]
        json['questions'] = quesArray
        console.log(searchContent)
        json['origin_question'] = searchContent
        if (quesArray.length <= 0) {
            alert('请在分解问题列表中选择若干问题')
            return
        }

        //绘制事件树但不改变currentOperationNode
        currentOperationNode['children'] = []
        var newChild = {
            'name': searchContent,
            'children': []
        }
        currentOperationNode['children'].push(newChild)
        refreshTree()

        questions = json
        initLayout()
        hideDetailAndShowList()
        // window.location.href="SearchResult.html?" + "content=" + encodeURI(JSON.stringify(json));
    });
});

$(document).ready(function(){
    $(".add_question").click(function(){
        count = $("#input_questions").children().length;
        console.log(count)
        $("#input_questions").append(`<div class="sub_question"><span class="decompose_title">子问题${count + 1}：</span><input onclick="clickInput(this)"><div onclick="deleteSubQuestion(this)" class="delete"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span><span class="end">删除</span></div></div>`)
    });
});